package com.website;

import com.alibaba.fastjson.JSON;
import com.website.common.vo.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * @author zhangshuw
 * <p>     2018/7/18
 */
@RestControllerAdvice
public class MvcControllerAdvice {

    @ExceptionHandler({Exception.class})
    public String handException(Exception exception) throws Exception {
        if (exception instanceof ConstraintViolationException) {
            return JSON.toJSONString(Result.error(exception.getMessage()));
        } else if (exception instanceof BindException) {
            BindException e = ((BindException) exception);
            FieldError error = e.getBindingResult().getFieldError();
            if (error != null) {
                return JSON.toJSONString(Result.error(error.getDefaultMessage()));
            }
        } else if (exception instanceof MissingServletRequestParameterException) {
            return JSON.toJSONString(Result.error(exception.getMessage()));
        }
        throw exception;
    }
}
